package cn.itsource.org.controller;

import cn.itsource.basic.utils.AjaxResult;
import cn.itsource.org.domain.Department;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author CTL
 * @Description
 * @date Created in 2023-05-16 14:37
 */

@RestController
@RequestMapping("/dept")
@Api(value = "DepartmentController",tags = {"部门管理"})
public class DepartmentController {
    @Autowired
    private IDepartmentService service;
    //查询所有
    @GetMapping("/getAll")
    public AjaxResult getAll() {
        return AjaxResult.createSuccess(service.getAll());
    }

    //分页查询
    @ApiOperation("获取所有数据")
    @PostMapping("/getPageList")
    public AjaxResult getPageList(@RequestBody DepartmentQuery query){
        //System.out.println(query.getParentId()+"================================"+query+query.getPageSize()+"===="+query.getPageNum());
        return AjaxResult.createSuccess(service.getPageList(query));
    }

    //添加修改
    @ApiOperation("添加修改")
    @PostMapping("/addOrUpdate")
    public AjaxResult addOrUpdate(@Validated @RequestBody Department department){
        try {
            service.addOrUpdate(department);
            return AjaxResult.createSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.createError("操作失败，有问题请联系管理员");
        }
    }

    //删除
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    public AjaxResult Delete(@PathVariable Long id){
        List<Department> departments = service.whetherItIsAParentDepartment(id);

        if(departments.size()>0){
            return AjaxResult.createError("此部门是父级部门，不能被删除");
        }

        service.delete(id);
        return AjaxResult.createSuccess();

    }
    @GetMapping("/treeDept")
    public AjaxResult treeDept(){
        return AjaxResult.createSuccess(service.treeDept());
    }


    @GetMapping("/getAllParentDepa")
    public AjaxResult getAllParentDepa(){
        return AjaxResult.createSuccess(service.getAllParentDepa());
    }
}
